package handel

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"gorm.io/gorm"
	"net/http"
	"post/api/gloab"
	"post/api/inits"
	"post/internal/model"
	req2 "post/internal/req"
	"post/pkg"
	"strconv"
)

func Chat(c *gin.Context) {
	userId := c.Query("user_id")
	userIdInt, _ := strconv.Atoi(userId)
	var conn, _ = gloab.Upgrader.Upgrade(c.Writer, c.Request, nil)
	var node = gloab.Node{
		Conn: conn,
		Data: make(chan []byte, 50),
	}
	gloab.ClitMap[userIdInt] = node
	go Red(node)
	go Wri(node)
}
func Red(node gloab.Node) {
	for {
		_, message, err := node.Conn.ReadMessage()
		if err != nil {
			return
		}
		var msg gloab.Msg
		err = json.Unmarshal(message, &msg)
		if err != nil {
			return
		}
		gloab.ClitMap[msg.DistId].Data <- message
	}
}
func Wri(node gloab.Node) {
	for {
		data := <-node.Data
		err := node.Conn.WriteMessage(websocket.TextMessage, data)
		if err != nil {
			return
		}
	}
}
func Comment(c *gin.Context) {
	var req req2.CommentReq
	c.ShouldBind(&req)
	userId, _ := c.Get("userId")
	userIdInt := userId.(int)
	var comment = model.Comment{
		UserId:  userIdInt,
		DistId:  req.VideoId,
		Content: req.Content,
	}
	var tx = inits.DB.Debug().Begin()
	tx.Create(&comment)
	bar := pkg.NewRabbitMQSimple("pot")
	marshal, err := json.Marshal(&comment)
	if err != nil {
		return
	}
	bar.PublishSimple(marshal)

	gloab.ClitMap[req.VideoId].Data <- []byte("一名用户评论了你")
	tx.Table("pots").Where("id = ?", req.VideoId).UpdateColumn("hot_num", gorm.Expr("hot_num + ?", 1))
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "评论成功",
		"data":    comment.ID,
	})
	tx.Commit()
}
